package com.bwie.es.service.impl;

import com.alibaba.fastjson2.JSON;
import com.bwie.common.core.utils.StringUtils;
import com.bwie.sku.domain.vo.SearchResult;
import com.bwie.es.service.EsService;
import com.bwie.sku.constant.SearchConstants;
import com.bwie.sku.domain.dto.SearchParam;
import com.bwie.spu.domain.SkuEsModel;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class EsServiceImpl implements EsService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 批量上传SkuEsModel到Elasticsearch
     * @param skuEsModelList SkuEsModel对象列表
     */
    @Override
    public boolean up(List<SkuEsModel> skuEsModelList) {
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.stream().forEach(skuEsModel -> {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("product");
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel),XContentType.JSON);

            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = null;
        try {
            bulk = client.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        boolean b = bulk.hasFailures();
        return b;
    }

    /**
     * 搜索skuEs
     * @param searchParam
     * @return
     */
    @Override
    public SearchResult getTableSkuInfo(SearchParam searchParam) throws IOException {
        //构建SearchRequest
        SearchRequest searchQuest = buildSearchRequest(searchParam);

        //执行search
        SearchResponse search = client.search(searchQuest, RequestOptions.DEFAULT);

        //解析response
        SearchResult searchResult = analyerResponse(search, searchParam);
        return searchResult;
    }

    private SearchResult analyerResponse(SearchResponse searchResponse, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        List skuEsModelList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            String skuEsModelString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(skuEsModelString, SkuEsModel.class);
            if (StringUtils.isNotBlank(searchParam.getKeyword())){
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField skuTitle = highlightFields.get("skuTitle");
                skuEsModel.setSkuTitle(skuTitle.getFragments()[0].toString());
            }
            skuEsModelList.add(skuEsModel);
        }
        searchResult.setProducts(skuEsModelList);
        searchResult.setPageNum(searchParam.getPageNum());
        searchResult.setTotal(hits.getTotalHits().value);
        searchResult.setTotalPages(Long.valueOf(searchResult.getTotal()%20==0?searchResult.getTotal()/20:(searchResult.getTotal()/20+1)).intValue());

        Aggregations aggregations = searchResponse.getAggregations();
        ParsedLongTerms brandIdAgg = aggregations.get("brandIdAgg");
        List<? extends Terms.Bucket> buckets = brandIdAgg.getBuckets();
        ArrayList<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(Long.valueOf(bucket.getKeyAsString()));
            Terms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogIdAgg = aggregations.get("catalogIdAgg");
        List<? extends Terms.Bucket> catalogBuckets = catalogIdAgg.getBuckets();

        for (Terms.Bucket catalogBucket : catalogBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String catalogId = catalogBucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(catalogId));
            Terms catalogNameAgg = catalogBucket.getAggregations().get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVo.setCatalogId(Long.valueOf(catalogId));
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogVos(catalogVos);

        ArrayList<SearchResult.AttrEsVo> attrs = new ArrayList<>();
        ParsedNested attrsAgg = aggregations.get("attrsAgg");
        Terms attrIdAgg = attrsAgg.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrEsVo attrVo = new SearchResult.AttrEsVo();
            String attrId = bucket.getKeyAsString();
            attrVo.setAttrId(Long.valueOf(attrId));

            Aggregations attrIdBucketAggregations = bucket.getAggregations();
            Terms attrNameAgg = attrIdBucketAggregations.get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            Terms attrValueAgg = attrIdBucketAggregations.get("attrValueAgg");
            List<String> values = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                values.add(attrValueAggBucket.getKeyAsString());
            }
            attrVo.setAttrValue(values);

            attrs.add(attrVo);

        }
        searchResult.setAttrVos(attrs);

        return searchResult;

    }


    /**
     * 构建SearchRequest
     * @param searchParam
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


//        if (StringUtils.isNotEmpty(searchParam.getKeyword())){
        if (searchParam.getKeyword()!=null && !searchParam.getKeyword().equals("")){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        if (searchParam.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        if (searchParam.getBrandId()!=null && searchParam.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }

        if (StringUtils.isNotBlank(searchParam.getSkuPrice())){
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            String[] split = searchParam.getSkuPrice().split("_");
            if (split.length==2){
                skuPrice.lte(split[1]);
                skuPrice.gte(split[0]);
            }else if (searchParam.getSkuPrice().startsWith("_")){
                skuPrice.lte(split[1]);
            }else if (searchParam.getSkuPrice().endsWith("_")){
                skuPrice.gte(split[0]);
            }
            boolQueryBuilder.filter(skuPrice);
        }

        if (searchParam.getAttrs()!=null && searchParam.getAttrs().size()>0){
            for (String attrStrs:searchParam.getAttrs()) {
                String[] splitAttrStr = attrStrs.split("_");
                Long attrId = Long.valueOf(splitAttrStr[0]);
                String[] attrValues = splitAttrStr[1].split(":");
                BoolQueryBuilder attrIdValueQueryBuilder = QueryBuilders.boolQuery();
                attrIdValueQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                attrIdValueQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs",attrIdValueQueryBuilder, ScoreMode.None));
            }
        }
        searchSourceBuilder.query(boolQueryBuilder);

        if (StringUtils.isNotBlank(searchParam.getSort())){
            String[] split = searchParam.getSort().split("_");
            searchSourceBuilder.sort(split[0],"asc".equalsIgnoreCase(split[1])? SortOrder.ASC:SortOrder.DESC);
        }

        searchSourceBuilder.from(searchParam.getPageNum());
        searchSourceBuilder.size(SearchConstants.PAGESIZE);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<span style='color:skyblue;front-size:18px'>");
        highlightBuilder.postTags("</span>");

        searchSourceBuilder.highlighter(highlightBuilder);

        TermsAggregationBuilder brandIdAgg = AggregationBuilders.terms("brandIdAgg").field("brandId");
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName");
        brandIdAgg.subAggregation(brandNameAgg);

        TermsAggregationBuilder catalogIdAgg = AggregationBuilders.terms("catalogIdAgg").field("catalogId");
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalogNameAgg").field("catalogName");
        catalogIdAgg.subAggregation(catalogNameAgg);

        NestedAggregationBuilder nested = AggregationBuilders.nested("attrsAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");

        nested.subAggregation(attrIdAgg);
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        searchSourceBuilder.aggregation(brandIdAgg);
        searchSourceBuilder.aggregation(catalogIdAgg);
        searchSourceBuilder.aggregation(nested);

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("product");
        searchRequest.source(searchSourceBuilder);
        return searchRequest;
    }
}
